package cn.wps.moffice.demo.fileManager;

import java.io.File;

import android.app.ListActivity;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import cn.wps.moffice.demo.util.Define;
import cn.wps.moffice.demo.util.SettingPreference;
import cn.wps.moffice.demo.util.Util;
import cn.wps.moffice.service.OfficeService;
import cn.wps.moffice.service.doc.Document;
import cn.wps.moffice.service.pdf.PDFReader;
import cn.wps.moffice.service.presentation.Presentation;
import cn.wps.moffice.service.spreadsheet.Workbook;

/**
 * @author ：chenyunbiao
 */
public class OpenFile {
	
	private final String LOG_TAG = ListActivity.class.getSimpleName();
	
	private static Document mDoc = null;
	private static PDFReader mPdfReader = null;
	private static Presentation mPresentation = null;
	private static Workbook mWorkbook = null;
	
	private OfficeService mService;
	private Context mContext;
	private static SettingPreference settingPreference;
	
	public OpenFile(OfficeService mService, Context mContext) {
		this.mService = mService;
		this.mContext = mContext;
	}
	
	public boolean openOtherFile(String path) {
		//第三方方式打开
		Intent intent = getOpenIntent(mContext, path, false);
		if (null == intent) {
			return false;
		}
		try {
			mContext.startActivity(intent);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public void openDocument(String path) {
		//AIDL方式打开
		if (mService == null) {
			return;
		}
		LoadDocThread docThread = new LoadDocThread(path);
		docThread.start();
	}
	
	class LoadDocThread extends Thread {
		String path;
		
		public LoadDocThread(String path) {
			this.path = path;
		}
		
		@Override
		public void run() {
			if (mService == null && !bindOfficeService()) {
				Util.showToast(mContext, "操作失败，service可能未正常连接");
				return;
			}
			try {
				Intent intent = getOpenIntent(mContext, path, true);
				if (Util.isExcelFile(path)) {
					mWorkbook = mService.getWorkbooks().openBookEx(path, "", intent);
					if (mWorkbook != null) {
						Util.showToast(mContext, "已打开excel文档");
					}
				} else if (Util.isPptFile(path)) {
					mPresentation = mService.openPresentation(path, "", intent);
					if (mPresentation != null) {
						Util.showToast(mContext, "已打开ppt文档");
					}
				} else if (Util.isPDFFile(path)) {
					mPdfReader = mService.openPDFReader(path, "", intent);
					if (mPdfReader != null) {
						Util.showToast(mContext, "已打开pdf文档");
					}
				} else {
					mDoc = mService.openWordDocument(path, "", intent);
					if (mDoc != null) {
						Util.showToast(mContext, "已打开word文档");
					}
				}
			} catch (RemoteException e) {
				mDoc = null;
				mPdfReader = null;
				mPresentation = null;
				mWorkbook = null;
				e.printStackTrace();
			}
		}
	}
	
	//获得文档打开需要设置的参数，参数都是由settingPreference存放的
  	public static Intent getOpenIntent(Context context, String path, boolean isAIDL)
  	{
  		settingPreference = new SettingPreference(context);
  		
  		String 	packageName   	= settingPreference.getSettingParam(Define.THIRD_PACKAGE, context.getPackageName()); 
  		
  		 //获得上次打开的文件信息
  		String 	closeFilePath 	= settingPreference.getSettingParam(Define.CLOSE_FILE, "null");  
  		float 	ViewProgress 	= settingPreference.getSettingParam(Define.VIEW_PROGRESS, (float)0.0);
  	    float 	ViewScale 		= settingPreference.getSettingParam(Define.VIEW_SCALE, (float)1.0);
  	    int 	ViewScrollX 	= settingPreference.getSettingParam(Define.VIEW_SCROLL_X, 0);
  	    int 	ViewScrollY 	= settingPreference.getSettingParam(Define.VIEW_SCROLL_Y ,0);
  		String 	userName        = settingPreference.getSettingParam(Define.USER_NAME, "newUser");
  		
  		 //获取用户设置的参数信息
	    String	OpenMode		= settingPreference.getSettingParam(Define.OPEN_MODE, Define.EDIT_MODE);
	    boolean SendSaveBroad   = settingPreference.getSettingParam(Define.SEND_SAVE_BROAD, false);
	    boolean SendCloseBroad  = settingPreference.getSettingParam(Define.SEND_CLOSE_BROAD, false);
	    boolean SendBackBroad   = settingPreference.getSettingParam(Define.BACK_KEY_DOWN, false);
	    boolean SendHomeBroad   = settingPreference.getSettingParam(Define.HOME_KEY_DOWN, false);
	    boolean IsIsClearBuffer = settingPreference.getSettingParam(Define.IS_CLEAR_BUFFER, false);
	    boolean IsClearTrace 	= settingPreference.getSettingParam(Define.IS_CLEAR_TRACE, false);
	    boolean IsClearFile 	= settingPreference.getSettingParam(Define.IS_CLEAR_FILE, false);
	    boolean IsViewScale     = settingPreference.getSettingParam(Define.IS_VIEW_SCALE ,false);
	    boolean AutoJump		= settingPreference.getSettingParam(Define.AUTO_JUMP, false);
	    boolean EnterReviseMode = settingPreference.getSettingParam(Define.ENTER_REVISE_MODE, false);
	    boolean CacheFileInvisible = settingPreference.getSettingParam(Define.CACHE_FILE_INVISIBLE, false);
	    boolean IsShowView      = settingPreference.getSettingParam(Define.IS_SHOW_VIEW, true);
	    boolean isCustomMenu    = false;//settingPreference.getSettingParam(Define.IS_CUSTOM_MENU, true);



		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		
		//满足AIDL方式打开只需第三方包名参数
		bundle.putString(Define.THIRD_PACKAGE, packageName);   //WPS回调需要靠这个参数找到第三方应用
		
		//更多参数设置
		bundle.putBoolean(Define.BACK_KEY_DOWN, SendBackBroad);      //Back键广播
		bundle.putBoolean(Define.HOME_KEY_DOWN, SendHomeBroad);      //Home键广播
		bundle.putBoolean(Define.SEND_CLOSE_BROAD, SendCloseBroad);	 //关闭文件的广播
		bundle.putString(Define.USER_NAME, userName);    //
		bundle.putBoolean(Define.CACHE_FILE_INVISIBLE, CacheFileInvisible);    //
//		bundle.putString(Define.WATERMASK_TEXT, "Test"); //水印字样
//		bundle.putInt(Define.WATERMASK_COLOR, Color.RED); //水印颜色
		
		bundle.putString(Define.OPEN_MODE, OpenMode);	//打开模式
		bundle.putBoolean(Define.IS_SHOW_VIEW, IsShowView);    //是否以显示界面方式打开
		bundle.putBoolean(Define.SEND_SAVE_BROAD, SendSaveBroad);    //保存文件的广播
		bundle.putBoolean(Define.CLEAR_BUFFER, IsIsClearBuffer);	 //清除临时文件
		bundle.putBoolean(Define.CLEAR_TRACE, IsClearTrace);		 //清除使用记录	
		bundle.putBoolean(Define.CLEAR_FILE, IsClearFile);           //删除打开文件
		bundle.putBoolean(Define.AUTO_JUMP, AutoJump);				 //自动跳转，包括页数和xy坐标
		bundle.putBoolean(Define.ENTER_REVISE_MODE, EnterReviseMode);    //是否默认进入修订模式
		bundle.putBoolean(Define.SHOW_REVIEWING_PANE_RIGHT_DEFAULT, false); // 侧边栏是否显示
		bundle.putBoolean(Define.IS_SCREEN_SHOTFORBID, false); //是否截屏
		
		//传入序列号
		bundle.putString(Define.SERIAL_NUMBER_OTHER, "BRAEWPRLXXLP2KGMUFGBRDHRB");
 		bundle.putString(Define.SERIAL_NUMBER_OTHERPC, "BRAEWPRLXXLP2KGMUFGBRDHRB");
//		bundle.putString(Define.SERIAL_NUMBER_OTHERPC, "RWX8XJVC34D3KPLEY3TYAU4YA");
//		bundle.putString(Define.SERIAL_NUMBER_OTHERPC, "RCYXKPM4CFMCQNGDFLG9WYQDL"); // 序列号过期
		
		//自定义菜单
//		if (isCustomMenu && isAIDL) {
//			bundle.putString(Define.MENU_XML, Util.assetsFileRead("menu.xml", context)); //显示自定义菜单
////			bundle.putString(Define.DISPLAY_OPEN_FILE_NAME, "Test.doc"); // 自定义菜单显示名称				
//		}
		
		if (path.equals(closeFilePath))	{ 					       //如果打开的文档是之前打开过的
			if (IsViewScale) {
				bundle.putFloat(Define.VIEW_SCALE, ViewScale);				//视图比例
			}	
			if (AutoJump) {
				bundle.putFloat(Define.VIEW_PROGRESS, ViewProgress);		//阅读进度
				bundle.putInt(Define.VIEW_SCROLL_X, ViewScrollX);			//x
				bundle.putInt(Define.VIEW_SCROLL_Y, ViewScrollY);			//y
			}
		}
		
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		//添加类名信息
		if (Util.checkPackage(context, Define.PACKAGENAME_KING_PRO)) {
			intent.setClassName(Define.PACKAGENAME_KING_PRO, Define.CLASSNAME);
		}
		else if (Util.checkPackage(context, Define.PACKAGENAME)) {
			intent.setClassName(Define.PACKAGENAME, Define.CLASSNAME);
		}
		else if (Util.checkPackage(context, Define.PACKAGENAME_KING_PRO_HW)) {
			intent.setClassName(Define.PACKAGENAME_KING_PRO_HW, Define.CLASSNAME);
		}
		else {
			Util.showToast(context, "文件打开失败，移动wps可能未安装");
			return null;
		}
		
		File file = new File(path);
		if (file == null || !file.exists()) {			
			Util.showToast(context, "打开失败，文件不存在！");
			return null;
		}
		
		Uri uri = Uri.fromFile(file);
		intent.setData(uri);
		intent.putExtras(bundle);
  		
  		settingPreference = null;
  		return intent;
  	}
	
	private  ServiceConnection connection = new ServiceConnection()
	{
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) 
		{
			mService = OfficeService.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) 
		{
			mService = null;
		}
	};
	
	private boolean bindOfficeService() {
		final Intent intent = new Intent(Define.PRO_OFFICE_SERVICE_ACTION);
		intent.setPackage("com.kingsoft.moffice_pro");
		intent.putExtra("DisplayView", true);
		boolean isbindService = false;
		try {
			isbindService = mContext.bindService(intent, connection, Service.BIND_AUTO_CREATE);
		} catch (SecurityException e) {
			Log.e(LOG_TAG, "绑定服务失败，请确认你安装的是企业版本！");
			throw e;
		}		
		if (!isbindService) {
			// bind failed, maybe wps office is not installed yet.
			mContext.unbindService(connection);
			return false;
		}
		return true;
	}
}
